package database

import (
	"heartbeat/database/schema"
	"heartbeat/utils"
	"log"

	"fmt"

	"github.com/go-xorm/xorm"
	_ "github.com/mattn/go-sqlite3"
)

var engine *xorm.Engine

func InitConnect() error {
	config := utils.GetConfig()
	var connectErr error
	engine, connectErr = xorm.NewEngine(config.Database.Driver, config.Database.Connect)
	if connectErr != nil {
		log.Fatalln(connectErr)
		return connectErr
	}
	if engine.Ping() != nil {
		return fmt.Errorf("数据库连接超时...")
	}

	log.Printf("数据库连接成功")
	err := engine.Sync2(new(schema.User))
	if err != nil {
		return fmt.Errorf("数据库同步User失败")
	}
	return nil
}

func GetDBConnect() *xorm.Engine {
	return engine
}
